import sys
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.utils import parseaddr, formataddr
from email.header import Header
from utils.get_config import configs

is_python3 = sys.version_info.major == 3
if is_python3:
    unicode = str


def _format_addr(data):
    name, addr = parseaddr(data)
    return formataddr((name, addr), charset='utf-8')


def _format_data(sender, recipient, subject, content, file_path):
    msg = MIMEMultipart()
    msg['From'] = _format_addr(u'报告人 <%s>' % sender)
    msg['To'] = _format_addr(u'管理人 <%s>' % recipient)
    msg['Subject'] = Header(subject, 'utf-8').encode()
    content = MIMEText(content, 'plain', 'utf-8')
    msg.attach(content)  # 邮件正文
    if file_path != '1' and file_path != '':
        att1 = MIMEText(open(file_path, 'rb').read(), 'base64', 'utf-8')  # 邮件附件
        file_path_list = file_path.strip().split('/')
        file_name = file_path_list[len(file_path_list) - 1]
        att1['Content-Type'] = 'application/octet-stream'
        att1['Content-Disposition'] = 'attachment; filename="' + file_name + '"'
        msg.attach(att1)
    return msg


def send_email(recipient, subject, content, file_path='1'):
    sender_host = configs['sender_host']  # 第三方 SMTP 服务
    sender_port = configs['sender_port']
    sender = configs['sender']
    sender_auth = configs['sender_auth']

    msg = _format_data(sender, recipient, subject, content, file_path)
    try:
        client = smtplib.SMTP_SSL(host=sender_host)  # 安全连接服务
        client.connect(sender_host, sender_port)
        client.set_debuglevel(1)
        client.login(sender, sender_auth)
        client.sendmail(sender, recipient.split(','), msg.as_string())
        client.quit()
        print('发送成功')
    except smtplib.SMTPConnectError as e:
        print('邮件发送失败，连接失败:', e.smtp_code, e.smtp_error)  # 可能连接地址、端口写错了
    except smtplib.SMTPAuthenticationError as e:
        print('邮件发送失败，认证错误:', e.smtp_code, e.smtp_error)  # 如果邮箱不支持ssl会报此错；邮箱需设置SMTP服务和授权码
    except smtplib.SMTPSenderRefused as e:
        print('邮件发送失败，发件人被拒绝:', e.smtp_code, e.smtp_error)
    except smtplib.SMTPRecipientsRefused as e:
        print('邮件发送失败，收件人被拒绝:', e.recipients)
    except smtplib.SMTPDataError as e:
        print('邮件发送失败，数据接收拒绝:', e.smtp_code, e.smtp_error)  # from和sender、to和recever必须一致
    except Exception as e:
        print('邮件发送异常, ', str(e))


if __name__ == '__main__':
    pass
    # recipient = '840213690@qq.com'  # 接收者，最多30个
    # subject = 'python测试报告2'
    # content = '你好！这是一封测试报告邮件，报告测试情况，请查收！'  # 发送内容
    # file_path = '../test_report/report1.html'  # 附件路径
    # send_email(recipient, subject, content, file_path)
